package com.seele.tigerwallet.ui.views;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter.RequestLoadMoreListener;
import com.seele.tigerwallet.R;
import com.seele.tigerwallet.api.APIException;
import com.seele.tigerwallet.api.APIListCallBack;
import com.seele.tigerwallet.api.APIModule;
import com.seele.tigerwallet.model.AssetsModel;
import com.seele.tigerwallet.model.MarketModel;
import com.seele.tigerwallet.model.WebModel;
import com.seele.tigerwallet.ui.activtiy.WebViewActivtiy;
import com.seele.tigerwallet.ui.adapter.MoreSreachAdapter;
import com.seele.tigerwallet.ui.adapter.MoreSreachAdapter.OnSreachClickListener;
import com.seele.tigerwallet.ui.callback.BaseListener;
import com.seele.tigerwallet.ui.callback.OnSelectListener;
import com.seele.tigerwallet.ui.utils.DividerItemDecoration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import retrofit2.Call;

public class AddMoreSearchRecyclerView extends RecyclerView implements RequestLoadMoreListener, OnSreachClickListener {


    private MoreSreachAdapter mMoreSreachAdapter;
    private List<MarketModel> mBundleList;//传值
    private int num = 50;
    private List<Integer> list = new ArrayList<>();
    private String mKeyword;

    private OnSelectListener onSelectListener;
    private View mErrorView;
    private View mEptyView;
    private boolean isEmpty;

    private Map<Integer, MarketModel> modelMap = new ConcurrentHashMap<>();
    private TextView mSubmitToken;


    public void setListener(BaseListener listener) {
        if (listener instanceof OnSelectListener) {
            this.onSelectListener = (OnSelectListener) listener;
        }

    }

    public AddMoreSearchRecyclerView(Context context) {
        this(context, null);
    }

    public AddMoreSearchRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AddMoreSearchRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    /**
     * @param context
     */
    private void initView(final Context context) {
        if (null == context) {
            return;
        }
        mErrorView = View.inflate(context, R.layout.search_error_view, null);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mErrorView.setLayoutParams(layoutParams);
        mSubmitToken = mErrorView.findViewById(R.id.submit_token);
        mSubmitToken.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                WebModel webModel = new WebModel();
                webModel.title =getResources().getString(R.string.cause);
                webModel.isDisplay = false;
                webModel.isHtmlTitle = false;
                webModel.url = APIModule.getTokeninfoURL();
                Bundle bundle = new Bundle();
                bundle.putSerializable(WebViewActivtiy.class.getSimpleName(), webModel);
                Intent intent=new Intent(context,WebViewActivtiy.class);
                intent.putExtras(bundle);
                context.startActivity(intent);

            }
        });


        mEptyView = View.inflate(context, R.layout.empty_view, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mEptyView.setLayoutParams(params);
        setLayoutManager(new LinearLayoutManager(context));

        if (null == mMoreSreachAdapter) {
            mMoreSreachAdapter = new MoreSreachAdapter(R.layout.item_add_more);
        }
        mMoreSreachAdapter.setOnSreachClickListener(this);
//        mMoreSreachAdapter.setOnLoadMoreListener(this, this);
//        mMoreSreachAdapter.setEnableLoadMore(true);
        setAdapter(mMoreSreachAdapter);

        mMoreSreachAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MarketModel item = null;
                if (null != mMoreSreachAdapter) {
                    item = mMoreSreachAdapter.getData().get(position);
                }
                switch (view.getId()) {
                    case R.id.check_ll:
                        onSelect(item);
                        break;
                }
            }
        });
//        initData(0, true);
    }

    public void addModel(MarketModel marketModel) {
        if (null != marketModel) {
            if (!modelMap.containsKey(marketModel.id)) {
                modelMap.put(marketModel.id, marketModel);
            }
        }
    }


    /**
     * 选择移除行情处理
     *
     * @param item
     */
    private void onSelect(MarketModel item) {
        if (null == item) {
            return;
        }
        boolean isOpen = item.isOpen;
        if (isOpen) {
            item.isOpen = false;
        } else {
            item.isOpen = true;
        }
        mMoreSreachAdapter.notifyDataSetChanged();
        if (null != mBundleList && mBundleList.size() > 0) {
            for (MarketModel marketModel : mBundleList) {
                list.add(marketModel.id);
            }
            if (item.isOpen) {
                if (!list.contains(item.id)) {
                    mBundleList.add(item);
                }
            } else {
                if (list.contains(item.id)) {
                    for (int i = mBundleList.size() - 1; i >= 0; i--) {
                        if (mBundleList.get(i).id == item.id) {
                            mBundleList.remove(i);
                        }
                    }
                }
            }
        } else {
            mBundleList = new ArrayList<>();
            mBundleList.add(item);

        }


        if (null != onSelectListener) {
            if (null != mBundleList) {
                onSelectListener.onSelect(mBundleList);
            }
        }
    }


    /**
     * 设置
     */
    public void setBundleList(List<MarketModel> bundleList, String keyword) {
        this.mBundleList = bundleList;


        if (null == bundleList) {
            bundleList = new ArrayList<>();
        }

        for (MarketModel marketModel : bundleList) {
            addModel(marketModel);
        }

        this.mKeyword = keyword;
        if (!TextUtils.isEmpty(mKeyword)){
            mKeyword = mKeyword.toString().trim();
        }
        if (TextUtils.isEmpty(mKeyword)) {
            mMoreSreachAdapter.setNewData(null);
            mMoreSreachAdapter.setEmptyView(mErrorView);
            isEmpty = true;
        } else {
            isEmpty = false;


            initDataForRank(mKeyword, 0, true);
        }
//        initData(mKeyword, 0, true);

    }


    @Override
    public void onLoadMoreRequested() {
        if (null != mMoreSreachAdapter) {
            List<MarketModel> assetsModels = mMoreSreachAdapter.getData();
            int size = assetsModels == null ? 0 : assetsModels.size();
            if (size > 0) {
//                int id = assetsModels.get(size - 1).id + 1;
//                initData(mKeyword, id, false);

                int rank = assetsModels.get(size - 1).rank + 1;
                initDataForRank(mKeyword, rank, false);

            }
        }

    }

    @Override
    public void onSwitchViewClick(int position, MarketModel item) {
        if (null != mMoreSreachAdapter) {
            mMoreSreachAdapter.getData().get(position).isOpen = item.isOpen;
        }
        if (null == mBundleList) {
            mBundleList = new ArrayList<>();
        }

        clear();
        for (MarketModel marketModel : mBundleList) {
            list.add(marketModel.id);
        }
        if (item.isOpen) {
            if (!list.contains(item.id)) {
                mBundleList.add(item);
            }
        } else {
            if (list.contains(item.id)) {
                for (int i = mBundleList.size() - 1; i >= 0; i--) {
                    if (mBundleList.get(i).id == item.id) {
                        mBundleList.remove(i);
                    }
                }
            }
        }
        if (null != onSelectListener) {
            if (null != mBundleList) {
                onSelectListener.onSelect(mBundleList);
            }
        }


    }

    /**
     * 请求数据
     *
     * @param keyword
     * @param id
     * @param isRefresh
     */
    private void initData(String keyword, int id, final boolean isRefresh) {

        APIModule
                .getApi()
                .searchQuotation(keyword, id, num)
                .enqueue(new APIListCallBack<MarketModel>() {
                    @Override
                    protected void onResponse(List<MarketModel> response) {
                        int size = response == null ? 0 : response.size();
                        //表示值为空
                        if (isEmpty) {
                            //设置空的View
                            mMoreSreachAdapter.setNewData(null);
                            mMoreSreachAdapter.setEmptyView(mEptyView);
                        } else {
                            if (isRefresh && size == 0) {
                                //设置搜索错误的View
                                mMoreSreachAdapter.setNewData(null);
                                mMoreSreachAdapter.setEmptyView(mErrorView);
                            } else {
                                handleData(response, isRefresh);
                            }

                        }

                    }

                    @Override
                    protected void onResponseError(APIException e) {


                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {


                    }


                });
    }


    /**
     * 请求数据
     *
     * @param keyword
     * @param rank
     * @param isRefresh
     */
    private void initDataForRank(String keyword, int rank, final boolean isRefresh) {

        APIModule
                .getApi()
                .searchQuotationRank(keyword, rank, num)
                .enqueue(new APIListCallBack<MarketModel>() {
                    @Override
                    protected void onResponse(List<MarketModel> response) {
                        int size = response == null ? 0 : response.size();
                        //表示值为空
                        if (isEmpty) {
                            //设置空的View
                            mMoreSreachAdapter.setNewData(null);
                            mMoreSreachAdapter.setEmptyView(mEptyView);
                        } else {
                            if (isRefresh && size == 0) {
                                //设置搜索错误的View
                                mMoreSreachAdapter.setNewData(null);
                                mMoreSreachAdapter.setEmptyView(mErrorView);
                            } else {
                                handleData(response, isRefresh);
                            }
                        }

                    }

                    @Override
                    protected void onResponseError(APIException e) {
                        if (!isRefresh) {
                            mMoreSreachAdapter.loadMoreFail();
                        }


                    }

                    @Override
                    protected void onFailureError(Call<String> call, Throwable t) {
                        if (!isRefresh) {
                            mMoreSreachAdapter.loadMoreFail();
                        }
                    }
                });
    }


    /**
     * 数据处理
     *
     * @param response
     * @param isRefresh
     */
    private void handleData(List<MarketModel> response, boolean isRefresh) {
        int size = response == null ? 0 : response.size();
        if (size > 0) {
            clear();



            for (MarketModel marketModel : response) {
                if (modelMap.containsKey(marketModel.id)) {
                    MarketModel model = modelMap.get(marketModel.id);
                    marketModel.isOpen=model.isOpen;
                }
            }

            if (isRefresh) {
                setAdapter(mMoreSreachAdapter);
                mMoreSreachAdapter.setNewData(response);
                mMoreSreachAdapter.notifyDataSetChanged();
            } else {
                mMoreSreachAdapter.addData(response);
                mMoreSreachAdapter.loadMoreComplete();
            }
        } else {
            if (isRefresh) {
                setAdapter(mMoreSreachAdapter);
                mMoreSreachAdapter.setNewData(response);
            }else {
                mMoreSreachAdapter.loadMoreEnd(isRefresh);
            }
        }
        mMoreSreachAdapter.notifyDataSetChanged();


    }

    private void clear() {
        if (list.size() > 0) {
            list.clear();
        }

    }

    public void setNormal() {
        mMoreSreachAdapter.setNewData(null);
        mMoreSreachAdapter.notifyDataSetChanged();
    }
}
